package com.maomao.annotation.excel;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author admin
 * @date 2018/4/17
 */
public class ExcelUtil<T> {
    private Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public List<T> importExcel(String sheetName, InputStream input) {
//        int maxCol = 0;
        List<T> list = new ArrayList<T>();
        try {
            Workbook workbook = WorkbookFactory.create(input);
            Sheet sheet = workbook.getSheet(sheetName);
            // 如果指定sheet名,则取指定sheet中的内容.
            if (!sheetName.trim().equals("")) {
                sheet = workbook.getSheet(sheetName);
            }
            // 如果传入的sheet名不存在则默认指向第1个sheet.
            if (sheet == null) {
                sheet = workbook.getSheetAt(0);
            }
            int rows = sheet.getPhysicalNumberOfRows();
            // 有数据时才处理
            if (rows > 0) {
                List<Field> allFields = getMappedFiled(clazz, null);
                // 定义一个map用于存放列的序号和field.
                Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
                // 第一行为表头
                Row rowHead = sheet.getRow(0);
                Map<String, Integer> cellMap = new HashMap<>();
                int cellNum = rowHead.getPhysicalNumberOfCells();
                for (int i = 0; i < cellNum; i++){
                    if (rowHead.getCell(i)!=null){
                        cellMap.put(rowHead.getCell(i).getStringCellValue().toLowerCase(), i);
                    }
                }
                for (Field field : allFields) {
                    // 将有注解的field存放到map中.
                    if (field.isAnnotationPresent(Excel.class)) {
                        Excel attr = field.getAnnotation(Excel.class);
                        // 根据Name来获取相应的failed
                        Integer col = cellMap.get(attr.name().toLowerCase());
                        if (col!=null){
                            field.setAccessible(true);
                            fieldsMap.put(col, field);
                        }
                    }
                }
                // 从第2行开始取数据
                for (int i = 1; i < rows; i++) {
                    Row row = sheet.getRow(i);
                    T entity = null;
                    for (int j = 0; j < cellNum; j++) {
                        Cell cell = row.getCell(j);
                        if (cell == null) {
                            continue;
                        }
                        CellType cellType=cell.getCellTypeEnum();
                        String c = "";
                        switch (cellType) {
                            case NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    c =sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                                }else {
                                    DecimalFormat df = new DecimalFormat("0");
                                    c = df.format(cell.getNumericCellValue());
                                }
                                break;
                            case BOOLEAN:
                                c = String.valueOf(cell.getBooleanCellValue());
                                break;
                            default:
                                //Excel Date类型处理
                                c = cell.getStringCellValue();
                                break;
                        }
                        if (c == null || c.equals("")) {
                            continue;
                        }
                        entity = (entity == null ? clazz.newInstance() : entity);
                        // 从map中得到对应列的field.
                        Field field = fieldsMap.get(j);
                        if (field == null) {
                            continue;
                        }
                        // 取得类型,并根据对象类型设置值.
                        Class<?> fieldType = field.getType();
                        if (String.class == fieldType) {
                            field.set(entity, String.valueOf(c));
                        } else if ((Integer.TYPE == fieldType)
                                || (Integer.class == fieldType)) {
                            field.set(entity, Integer.valueOf(c));
                        } else if ((Long.TYPE == fieldType)
                                || (Long.class == fieldType)) {
                            field.set(entity, Long.valueOf(c));
                        } else if ((Float.TYPE == fieldType)
                                || (Float.class == fieldType)) {
                            field.set(entity, Float.valueOf(c));
                        } else if ((Short.TYPE == fieldType)
                                || (Short.class == fieldType)) {
                            field.set(entity, Short.valueOf(c));
                        } else if ((Double.TYPE == fieldType)
                                || (Double.class == fieldType)) {
                            field.set(entity, Double.valueOf(c));
                        } else if (Character.TYPE == fieldType) {
                            if (c.length() > 0) {
                                field.set(entity, c.charAt(0));
                            }
                        }
                    }
                    if (entity != null) {
                        list.add(entity);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 得到实体类所有通过注解映射了数据表的字段
     *
     * @param clazz
     * @param fields
     * @return
     */
    private List<Field> getMappedFiled(Class clazz, List<Field> fields) {
        if (fields == null) {
            fields = new ArrayList<Field>();
        }
        // 得到所有定义字段
        Field[] allFields = clazz.getDeclaredFields();
        // 得到所有field并存放到一个list中.
        for (Field field : allFields) {
            if (field.isAnnotationPresent(Excel.class)) {
                fields.add(field);
            }
        }
        if (clazz.getSuperclass() != null
                && !clazz.getSuperclass().equals(Object.class)) {
            getMappedFiled(clazz.getSuperclass(), fields);
        }

        return fields;
    }

}
